import jaydebeapi
import sys
from libs.read_config import read_ini_value


class OceanDb:
    def __init__(self):
        self.url = read_ini_value('oceanbase', 'url')
        self.driver = read_ini_value('oceanbase', 'driver')
        self.jar_file = read_ini_value('oceanbase', 'jar_file')
        self.user = read_ini_value('oceanbase', 'user')
        self.password = read_ini_value('oceanbase', 'password')

    def _get_connect(self):
        try:
            self.conn = jaydebeapi.connect(self.driver, self.url, [self.user, self.password], self.jar_file)
            # print("成功连接到 OceanBase 数据库的 Oracle 模式")
            self.cursor = self.conn.cursor()
            # print("成功获取cursor游标")
            return self.cursor
        except jaydebeapi.Error as error:
            print(f"连接数据库时出错: {error}")

    def query(self, sql):
        cursor = self._get_connect()
        cursor.execute(sql)
        column_names = [desc[0] for desc in cursor.description]
        # print("字段名称:", column_names)
        results = cursor.fetchall()
        row_dict = None
        for row in results:
            row_dict = dict(zip(column_names, row))
            # print(row_dict)
        self._close_connect()
        return row_dict

    def execute_sql(self, sql):
        cursor = self._get_connect()
        cursor.execute(sql)
        self.cursor.close()
        self.conn.close()

    def _close_connect(self):
        self.cursor.close()
        self.conn.close()


if __name__ == '__main__':
    # db = OceanDb()
    # db.query('select * from BUPPS_BAFFLE_HOST_ACCOUNT')
    print(sys.platform)
